<template>
  <div class="department-management-container">
    <div
      style="
        color: #fa6567;
        font-weight: bold;
        font-size: 18px;
        margin-bottom: 20px;
        margin-left: 10px;
      "
    >
      【特殊权限】的菜单不允许被修改、删除，仅超级管理员拥有此权限，该权限无法分配给普通管理员；
      <br />
      【移动】菜单仅可在当前层级内移动，移动后需刷新系统才会更新左侧菜单。
    </div>
    <vab-query-form>
      <vab-query-form-left-panel :span="12">
        <el-button
          icon="el-icon-plus"
          style="
            background-color: #58b5e1;
            color: #fff;
            border: 0px;
            font-size: 14px;
          "
          @click="handleEdit($event)"
        >
          添加
        </el-button>
        <el-button
          icon="el-icon-delete"
          style="
            background-color: #fa6567;
            color: #fff;
            border: 0px;
            font-size: 14px;
          "
          @click="handleDelete($event)"
        >
          批量删除
        </el-button>
      </vab-query-form-left-panel>
      <vab-query-form-right-panel :span="12">
        <el-form :inline="true" :model="queryForm" @submit.prevent>
          <el-form-item>
            <el-input
              v-model.trim="queryForm.name"
              clearable
              placeholder="请输入名称"
              @keydown.enter="searchText(queryForm.name)"
            />
          </el-form-item>
          <el-form-item>
            <el-button
              icon="el-icon-search"
              style="
                background-color: #58b5e1;
                color: #fff;
                border: 0px;
                font-size: 14px;
              "
              @click="searchText(queryForm.name)"
            >
              查询
            </el-button>
          </el-form-item>
        </el-form>
      </vab-query-form-right-panel>
    </vab-query-form>

    <el-table
      v-loading="listLoading"
      border
      :cell-style="{ padding: '4px 0 4px 0' }"
      :data="list"
      default-expand-all
      :header-cell-style="{
        background: '#E1EAF3 !important',
        'text-align': 'center',
      }"
      :height="600"
      row-key="id"
      :row-style="{ background: '#E4F2FF' }"
      stripe
      :tree-props="{ children: 'children' }"
      @selection-change="setSelectRows"
    >
      <el-table-column
        :selectable="checkIsUnDisabled"
        show-overflow-tooltip
        type="selection"
      />
      <el-table-column label="名称" prop="title" show-overflow-tooltip>
        <template #default="{ row }">
          {{ row.index + '&ensp;' }}
          <vab-icon :icon="row.icon" />
          {{ row.title }}
        </template>
      </el-table-column>
      <el-table-column label="路由" prop="path" show-overflow-tooltip />
      <el-table-column label="组件" prop="component" show-overflow-tooltip />
      <el-table-column
        align="center"
        label="创建时间"
        prop="createTime"
        show-overflow-tooltip
        width="100"
      >
        <template #default="{ row }">
          {{ row.createTime }}
        </template>
      </el-table-column>
      <el-table-column
        align="center"
        label="更新时间"
        prop="updateTime"
        show-overflow-tooltip
        width="100"
      >
        <template #default="{ row }">
          {{ row.updateTime }}
        </template>
      </el-table-column>
      <el-table-column align="center" fixed="right" label="操作" width="160">
        <template #default="{ row }">
          <el-button
            :disabled="!row.hasPreNeighbor"
            type="text"
            @click="sortRow(row, -1)"
          >
            上移
          </el-button>
          <el-button
            :disabled="!row.hasNextNeighbor"
            type="text"
            @click="sortRow(row, 1)"
          >
            下移
          </el-button>
          <el-button type="text" @click="handleEdit(row)">编辑</el-button>
          <el-button
            :disabled="row.disabled === 1"
            type="text"
            @click="handleDelete({ row })"
          >
            删除
          </el-button>
          <!-- <el-button
            v-show="row.disabled === 1"
            :disabled="row.disabled === 1"
            type="text"
            @click="handleDelete({ row })"
          >
            不可操作
          </el-button> -->
        </template>
      </el-table-column>
      <template #empty>
        <el-empty
          class="vab-data-empty"
          description=" "
          :image="require('@/assets/empty_images/data_empty.png')"
          :image-size="250"
        />
      </template>
    </el-table>
    <el-pagination
      background
      :current-page="queryForm.pageNo"
      :layout="layout"
      :page-size="queryForm.pageSize"
      :page-sizes="[30, 40, 50, 100]"
      :total="total"
      @current-change="handleCurrentChange"
      @size-change="handleSizeChange"
    />
    <edit ref="editRef" @fetch-data="fetchData" />
  </div>
</template>

<script>
  import {
    defineComponent,
    getCurrentInstance,
    onMounted,
    reactive,
    toRefs,
  } from 'vue'
  import { getList } from '@/api/router'
  import { doDelete } from '@/api/system_rule'
  import { doSortChange } from '@/api/system_rule'
  import Edit from './components/DepartmentManagementEdit'
  import moment from '_moment@2.29.1@moment'
  import $ from 'jquery'

  export default defineComponent({
    name: 'DepartmentManagement',
    components: { Edit },
    setup() {
      const { proxy } = getCurrentInstance()

      const state = reactive({
        editRef: null,
        list: [],
        listLoading: true,
        layout: 'total, sizes, prev, pager, next, jumper',
        total: 0,
        selectRows: '',
        queryForm: {
          pageNo: 1,
          pageSize: 30,
          title: '',
        },
      })

      const setSelectRows = (val) => {
        state.selectRows = val
      }
      const handleEdit = (row) => {
        if (row.id) {
          state.editRef.showEdit(row)
        } else {
          state.editRef.showEdit()
        }
      }
      const handleDelete = (rowTemp) => {
        console.log(rowTemp)
        let row = rowTemp.row
        if (row && row.id) {
          proxy.$baseConfirm('你确定要删除当前项吗', null, async () => {
            const { msg } = await doDelete({ ids: row.id })
            proxy.$baseMessage(msg, 'success', 'vab-hey-message-success')
            await fetchData()
          })
        } else {
          if (state.selectRows.length > 0) {
            const ids = state.selectRows.map((item) => item.id).join()
            proxy.$baseConfirm('你确定要删除选中项吗', null, async () => {
              const { msg } = await doDelete({ ids })
              proxy.$baseMessage(msg, 'success', 'vab-hey-message-success')
              await fetchData()
            })
          } else {
            proxy.$baseMessage('未选中任何行', 'error', 'vab-hey-message-error')
          }
        }
      }
      const sortRow = async (row, todo) => {
        let targetIndex
        if (row.index.toString().includes('-')) {
          let handleIndex = row.index.split('-')
          targetIndex =
            handleIndex[0] + '-' + (parseInt(handleIndex[1]) + parseInt(todo))
        } else {
          targetIndex = parseInt(row.index) + todo
        }

        let targetId = 0
        let targetName
        state.list.forEach((first) => {
          if (first.index == targetIndex) {
            targetId = first.id
            targetName = first.name
          }
          if (first.children && first.children.length > 0) {
            first.children.forEach((second) => {
              if (second.index == targetIndex) {
                targetId = second.id
                targetName = second.name
              }
            })
          }
        })
        proxy.$baseConfirm(
          '你确定要将【' +
            row.name +
            '】在当前层级内' +
            (todo.toString().includes('-') ? '上移' : '下移') +
            '，并与【' +
            targetName +
            '】交换位置吗',
          null,
          async () => {
            await doSortChange({
              id: row.id,
              targetId: targetId,
            })
            fetchData()
          }
        )
      }
      const checkIsUnDisabled = (row) => {
        return row.disabled === 0
      }
      const handleSizeChange = (val) => {
        state.queryForm.pageSize = val
        fetchData()
      }
      const handleCurrentChange = (val) => {
        state.queryForm.pageNo = val
        fetchData()
      }
      const queryData = () => {
        state.queryForm.pageNo = 1
        fetchData()
      }
      const fetchData = async () => {
        state.listLoading = true
        const {
          data: { list, total },
        } = await getList()
        state.list = setList(list)
        //为了排序，处理一下，保证可移动均合理
        let index = 0
        state.list.forEach((first) => {
          first.hasPreNeighbor = index != 0
          first.hasNextNeighbor = index != list.length - 1
          index++
          let indexS = 0
          first.index = index
          if (first.children && first.children.length > 0) {
            first.children.forEach((second) => {
              second.hasPreNeighbor = indexS != 0
              second.hasNextNeighbor = indexS != first.children.length - 1
              indexS++
              second.index = first.index + '-' + indexS
            })
          }
        })
        state.total = total
        state.listLoading = false
      }
      const setList = (list) => {
        for (let i = 0; i < list.length; i++) {
          if (list[i].children.length === 0) {
            list[i].children = null
          } else {
            list[i].children = setList(list[i].children)
          }
        }
        return list
      }
      const searchText = (str) => {
        if (!str) {
          proxy.$baseMessage(
            '请输入内容以搜索',
            'warn',
            'vab-hey-message-error'
          )
          return false
        }
        var Count = 0
        $('table')
          .find('tbody tr td')
          .each(function () {
            var text = $(this).text()
            console.log(text + '---' + str)
            if (text.indexOf(str) != -1) {
              //首先将选中的元素获取，修改样式
              $(this).css('background-color', 'rgba(250,230,160,05)')
              setTimeout(() => {
                $(this).css('background-color', 'rgba(0,0,0,0)')
              }, 600)
              if (Count == 0) {
                $('#app').stop(true)
                $('#app').animate(
                  { scrollTop: $(this).offset().top - 120 },
                  200
                )
              }
              Count++
            }
          })
        if (Count == 0) {
          proxy.$baseMessage('未查询到内容', 'warn', 'vab-hey-message-error')
        }
      }
      onMounted(() => {
        fetchData()
      })

      return {
        ...toRefs(state),
        searchText,
        setSelectRows,
        handleEdit,
        handleDelete,
        handleSizeChange,
        handleCurrentChange,
        queryData,
        fetchData,
        checkIsUnDisabled,
        sortRow,
      }
    },
    computed: {},
    methods: {
      formatDates(dateStr) {
        let pattern = 'YYYY-MM-DD'
        return moment(parseInt(dateStr + '000')).format(pattern)
      },
    },
  })
</script>
